#!/usr/bin/perl -w
use warnings;
use strict;
use Pod::Usage;
use Data::Dumper;
use Storable qw(retrieve);
BEGIN {
    use File::Basename;
    my $path = dirname($0);
    $path = '.' unless defined $path && $path ne '';
    #print STDERR "pushing INC path: [$path]\n";
    push @INC, $path;
}

### user modules
#use LogParse;
#use DataName;
use HtmlReport;
#use FieldHash;
use CommandLine;
use SimpleError;

### options definition
my %options = (
    'wafer-data'     => +{ option => 'wafer-data|i|w=s'      , value =>    undef, check => 1 },
    'stats-data'     => +{ option => 'stats-data|s=s'        , value =>    undef, },
    'output'         => +{ option => 'output|o=s'            , value =>    undef, },
    #--
    'wafer-list'     => +{ option => 'wafer-list|l:s'        , value =>    undef, },
    'notes'          => +{ option => 'notes|n=s'             , value =>    undef, },
    #--
    'help'           => +{ option => 'help|h|?'              , value =>    undef, },
    'manual'         => +{ option => 'manual'                , value =>    undef, },
);
use constant OPTION_DEFAULT => '.';
my %option_defaults = (
    'output'         => +{ reference => 'wafer-data', value => '*.report.html'       , base => 1, },
    'stats-data'     => +{ reference => 'wafer-data', value => '*.analysis.dat'      , base => 1, },
    'notes'          => +{ reference => 'wafer-data', value => '@*.notes.txt'         , base => 1, },
);

### command line interface
pod2usage(-exitstatus => 0, -verbose => 1) if @ARGV == 0;
CommandLine::get_options( \%options, 'config' );
pod2usage(-exitstatus => 0, -verbose => 1) if $options{'help'}{'value'};
pod2usage(-exitstatus => 0, -verbose => 2) if $options{'manual'}{'value'};
CommandLine::apply_checks( \%options );
CommandLine::apply_defaults( \%option_defaults,  \%options, OPTION_DEFAULT );
#message( "options with defaults applied:" );
#CommandLine::print_options( \%options );

### main
my ($wafer_data, $stats_data);
message("reading wafer data: $options{'wafer-data'}");
$wafer_data = retrieve($options{'wafer-data'}{value})
    or error("cannot retrieve wafer data: $options{'wafer-data'}{vlaue}");
if (defined($options{'stats-data'}{value})) {
    message("reading stats data: $options{'stats-data'}");
    $stats_data = retrieve($options{'stats-data'}{value})
        or error("cannot retrieve wafer data: $options{'stats-data'}{vlaue}");
    ## safety check
    error("lot number not match between wafer data and stats data")
        unless ($wafer_data->{Lot_Number} eq $stats_data->{Lot_Number});
}
my $output_file;
if (defined $options{output}{value}) {
    $output_file = $options{output}{value};
    open OUTPUT, '>', $output_file or error("cannot output to '$output_file': $!");
    select OUTPUT;
} else {
    $output_file = '<STDOUT>';
}
my $notes = $options{notes}{value};
if (defined($notes)) {
    if (substr($notes, 0, 1) eq '@') {
        $notes = substr($notes, 1);
        open my $fh, '<', $notes or error("$notes: cannot read notes: $!");
        local $/;
        $notes = <$fh>;
        close $fh;
    }
}
my $wafer_list = create_wafer_no_list($options{'wafer-list'}{value}, $wafer_data->{Wafer_Number});

my $html_gen = HtmlReport::->new();
$html_gen->set(Wafer_List => $wafer_list, Output_File => $output_file);
$html_gen->set(Notes => $notes);
$html_gen->set_data($wafer_data, $stats_data);
print $html_gen->output();

close OUTPUT if $output_file ne '<STDOUT>';
exit 0;

# =============================================================
# S u b r o u t i n e s
# =============================================================

sub create_wafer_no_list {
    my ($value, $this_no) = @_;
    message("getting value: [$value]");
    return undef unless (defined($value));
    return [ (1 .. 25) ] if $value eq '';
    unless ($value =~ /^\s*(?:[\d]{1,2}(?:-[\d]{1,2})?)(?:,[\d]{1,2}(?:-[\d]{1,2})?)*\s*$/) {
        error("wafer-list option spec is invalid.");
    }
    ## comma separated items
    my @clist = split ',', $value;
    my @no_list = ($this_no);
    for my $a (@clist) {
        $a =~ /(\d+)(?:-(\d+))?/;
        my ($begin, $end) = ($1, $2);
        if (defined($end)) {
            error("range spec is not incremental: $begin-->$end") unless $begin <= $end;
            push @no_list, ($begin .. $end);
        } else {
            push @no_list, $a;
        }
    }
    my %unique;
    $unique{$_} = 1 for @no_list;
    return [
        sort {; $a <=> $b; } keys(%unique)
    ];
}

__END__

=head1 NAME

=over 2

genhtml

=back

=head1 SYNOPSIS

Generates HTML report.

=head1 Common Usage Scenarios

=over 2

=back

=head1 OPTIONS

=over 2

=item *

-i, --input=FILE
Specify input.

=item *

-o, --output=FILE
Specify output.

=item *

-t, --separator=STRING
Specify separating string.

=back

=head1 DESCRIPTION

=cut
